package com.zf.study.server;

import com.zf.study.handler.ChatHandler;
import com.zf.study.handler.HeartBeatHandler;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ChatServer {


    /**
     * 线程池执行器实例
     * <p>
     * 核心线程数: 5
     * 最大线程数: 10
     * 空闲线程存活时间: 1000毫秒
     * 工作队列: 容量为20的数组阻塞队列
     * 线程工厂: 自定义线程工厂MyThreadFactory
     * 拒绝策略: 直接抛出异常的中止策略
     */
    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
            10,
            1000,
            TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(20),
            new MyThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    private static final Map<String,PrintWriter> allClientWriters = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String,String> userMap = new ConcurrentHashMap<>();





    public void init() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8088);
        threadPoolExecutor.execute(new HeartBeatHandler());
        int count = 1;
        while (true) {
            Socket socket = serverSocket.accept();
            threadPoolExecutor.execute(new ChatHandler("tag" + count++, socket,allClientWriters,userMap));
        }
    }

    public static void main(String[] args) throws IOException {
        new ChatServer().init();
    }


    /**
     * 自定义线程工厂
     */
    static class MyThreadFactory implements ThreadFactory {
        private static  AtomicInteger count = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("MyThread--" + count.getAndIncrement());
            thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    }
}
